/**
 * © 2012 HaoTu.la
 */
var col = document.getElementsByTagName("script");
var jsrc = col.item(col.length-1).src; 
var i = jsrc.indexOf("?"); 
var params = jsrc.substr(i + 1, jsrc.length).replace('&amp;', '&').split('&');
var comment = {};
comment.params = [],
comment.url = '/comment';
comment.data = [];
comment.currentPage = 1;
comment.postFunc = function(){};
for(var key in params) {
	var s = params[key];
	var n = s.substring(0, s.indexOf('='));
	var v = decodeURIComponent(s.substring(s.indexOf('=') + 1));
	if(n == 'params') {
		comment.params = v.split('&');
	} else {
		comment[n] = v;
	}
}
comment.loading = 'Loading..';

comment.keydown = function(e) {
	if((e.keyCode == 13 && e.ctrlKey == true) || (e.altKey == true && e.keyCode == 83)) {
		this.post($('#commentButton'));
		return false;
	}
};

comment.load = function(pid, firstLoad) {
	var page = typeof(pid) == 'undefined' ? 1 : parseInt(pid);
	if(typeof(this.data[page]) != 'undefined') {
		$('#' + this.id).html(this.data[page]);
		return false;
	}
	var first = typeof(firstLoad) == 'undefined' ? false : true;
	if(!first) {
		$('#' + this.id).html(this.loading);
	} else {
		this.loading = $('#' + this.id).html();
	}
	var data = [];
	for(var pi in this.params) {
		data.push(this.params[pi]);
	}
	data.push('page=' + page);
	data.push('ns=true');
	data.push('r=' + Math.random().toString().replace('.', '_'));
	var self = this;
	$.ajax({type:'POST',dataType:'json',url:this.url,data:data.join('&'),success:function(json, status){
		try {
			if(json.status == 0) {
				throw json;
			}
			if(typeof(json.html) == 'undefined') {
				_error('Load comment failed.');
			} else {
				self.currentPage = page;
				self.data[page] = json.html;
				$('#' + self.id).html(self.data[page]);
			}
		} catch (e) {
			_error(e.message);
		}
	}, error: function (req, msg, e) {
		_error(req['statusText']);
	}, timeout: 30000});
	return false;
	
	function _error(msg) {
		alert(msg);
	}
};

comment.reply = function(rid) {
	$('#comment-quote').show().find('em').text($('#comment-message-' + rid).text());
	$('input[name=reply_id]').val(rid);
	$('textarea[name=message]').focus();
	return false;
};

comment.unreply = function() {
	$('#comment-quote').hide();
	$('input[name=reply_id]').val(0);
	$('textarea[name=message]').focus();
	return false;
};

comment.like = function(cid) {
	var _like = parseInt($('#like-' + cid).html());
	$('#like-' + cid).text((_like + 1).toString());
	var data = [];
	for(var pi in this.params) {
		data.push(this.params[pi]);
	}
	data.push('submit=like');
	data.push('comment_id=' + cid);
	data.push('r=' + Math.random().toString().replace('.', '_'));
	$.ajax({type:'POST',dataType:'json',url:this.url,data:data.join('&'),success:function(json, status){}});
	return false;
};

comment.reset = function(btn) {
	var form = btn.parents('form');
	if(form.length == 0) {
		alert('NO FORM FOUND!');
		return false;
	}
	btn.html(btn.attr('_text'));
	btn.removeAttr('disabled');
	form.find('button[type=reset]').eq(0).click();
	comment.unreply();
};

comment.post = function(btn) {
	var form = btn.parents('form');
	if(form.length == 0) {
		alert('NO FORM FOUND!');
		return false;
	}
	var textarea = $('textarea[name=message]');
	if(textarea.val() == '') {
		alert('Please Enter the comment message.');
		textarea.focus();
		return false;
	}
	var _url = form.attr('action');
	var params = [];
	var serializeData = form.serializeArray();
	for(var i in serializeData) {
		params.push(serializeData[i]['name'] + '=' + encodeURIComponent(serializeData[i]['value']));
	}
	var _data = params.join('&');
	$.ajax({type:'POST',dataType:'json',url:_url,data:_data,success:function(json, status){
		try {
			if(json.status == 0) {
				throw json;
			}
			_success(json);
		} catch (e) {
			_error(e.message);
		}
	}, error: function (req, msg, e) {
		_error(req['statusText']);
	}, beforeSend: function(req) {
		btn.attr('_text', btn.html());
		btn.html('Posting ...');
		btn.attr('disabled', 'disabled');
	}, timeout: 30000});
	return false;
	
	function _success(json) {
		comment.reset(btn);
		comment.data = [];
		comment.load(comment.currentPage, true);
		comment.postFunc();
		$('.commentMsg h3').html(json.message);
		$('.commentMsg code a').click(function(){$('.commentMsg').fadeOut('fast');});
		$('.commentMsg').show();
		setInterval(function(){
			$('.commentMsg').fadeOut('fast');
		}, 3000);
	}
	
	function _error(msg) {
		btn.html(btn.attr('_text'));
		btn.removeAttr('disabled');
		alert(msg);
	}
};
